package org.example.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.example.netty.common.MyDecoder;
import org.example.netty.common.MyEncoder;
import org.example.netty.common.MyMessage;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Scanner;

@Component
public class NettyClientInit implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();  //客户端只需要一个loopGroup

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new MyDecoder());
                            channel.pipeline().addLast(new MyEncoder());
                            channel.pipeline().addLast(new SimpleChannelInboundHandler<MyMessage>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyMessage myMessage) throws Exception {
                                    System.out.println("Received from server: " + myMessage.getContent());
                                }
                            });
                        }
                    });

            ChannelFuture f = bootstrap.connect("localhost",8080).sync();

            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("Connected to server");
                    }else {
                        System.out.println("Failed to connect to server");
                        channelFuture.cause().printStackTrace();
                    }
                }
            });

            Scanner scanner = new Scanner(System.in);
            while(true){
                System.out.println("请输入要发送的消息，quit代表停止发送！");
                String input = scanner.nextLine();
                if ("quit".equals(input)) {
                    break;
                }
                MyMessage message = new MyMessage(input);
                f.channel().writeAndFlush(message);
            }
            f.channel().closeFuture().sync();

        }finally {
            group.shutdownGracefully();
        }
    }
}
